package cn.wangkai.peanut.commons.beanutils;

import java.math.BigDecimal;

import org.apache.commons.beanutils.ConversionException;
import org.apache.commons.beanutils.Converter;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class BigDecimalConverter implements Converter {

	private static final Log log = LogFactory.getLog(BigDecimalConverter.class);
	
	public BigDecimalConverter() {
	}
	
	public static BigDecimal tobigdecimal(String value){
		if(StringUtils.isBlank(value)) {
			return null;
		}
		try {
			return new BigDecimal(value);
		} catch (Exception e) {
			return null;
		}
	}
	
	@SuppressWarnings("rawtypes")
	public Object convert(Class type, Object value) {
		log.debug("type="+type+"||value="+value);
		if(value==null||StringUtils.isBlank(value.toString())) {
			return null;
		}

		if(value instanceof BigDecimal) {
			return value;
		} else if(value instanceof Long) {
			Long longValue = (Long) value;
			return new BigDecimal(longValue);
		} else if(value instanceof Integer) {
			Integer intval = (Integer) value;
			return new BigDecimal(intval);
		}

		try {
			String strval = value.toString();
			return new BigDecimal(strval);
		} catch (Exception e) {
			throw new ConversionException(e);
		}
	}
	
	public static void main(String[] args) {

	}

}
